/*
DailyBread.m - Copyright (c) 1992 NeXT Computer, Inc.

You may freely copy, distribute and reuse the code in this example.
NeXT Computer, Inc. disclaims any warranty of any kind, expressed or implied, 
as to its fitness for any particular use.
*/
 
#import	<appkit/appkit.h> 
#import	<objc/hashtable.h>
#import	"DailyBread.h"
#import	"IXStringSearch.h"

@implementation DailyBread

- initForDate:(const char *)theDate
{
    int   i;

    [super init];
    _changed = YES;
    _theDate = NXCopyStringBuffer(theDate);
    upperLimit = 7;
    for (i = 0; i < DBR_MAXFIELDS; i++) {
	doneFields[i] = TRUE;
	_number[i] = NXCopyStringBuffer("");
    }

    _theStringValue = NXCopyStringBuffer("");
    return self;
}

- free
{
    int  i;

    free(_theDate);
    for (i = 0; i < DBR_MAXFIELDS; i++)
	free(_number[i]);

    free(_theStringValue);
    return[super free];
}

- (char *)theDate
{
    return _theDate;
}

- setNumber:(int)i to:(const char *)aString
{
    _changed = YES;
    if (strlen(_number[i]) > 0)
	free(_number[i]);

    _number[i] = NXCopyStringBuffer(aString ? aString : "");
    return self;
}

- (char *)number:(int)i
{
    return (i < DBR_MAXFIELDS) ? _number[i] : "";
}

- setDone:(int)i to:(int)yn
{
    _changed = YES;
    doneFields[i] = yn ? YES : NO;
    return self;
}

- (int)done:(int)i
{
    return (i < DBR_MAXFIELDS) ? doneFields[i] : 0;
}

- (float)textGrayOfNumber:(int)i
{
    return textGrays[i];
}

- setNumber:(int)i textGray:(float)gVal
{
    textGrays[i] = gVal;
    return self;
}

- (const char *)stringValue
{
    char   *theResult;
    int    sLength, i;

    sLength = 0;
    if (_changed == YES) {
	if (strlen(_theStringValue) > 0)
	    free(_theStringValue);

	for (i = 0; i < upperLimit; i++)
	    sLength += (2+strlen(_number[i]));

	theResult = (char *)malloc(sLength+20);
	strcpy(theResult, _theDate);
	strcat(theResult, "\n");
	for (i = 0; i < upperLimit; i++) {
	    strcat(theResult, _number[i]);
	    strcat(theResult, "\n");
	}

	_theStringValue = theResult;
	_changed = NO;
    };

    return _theStringValue;
}

- (const char *)midlingStringValueFor:(const char *)aWord
{
    IXBMTable	*theEngine;

    // yup, this is undocumented. it does what any BoyerMoore search might do.*/
    theEngine = IXBMCompile(aWord, YES);
    return IXBMMatch(_theStringValue, strlen(_theStringValue), theEngine);
}

- source:aSource didReadRecord:(unsigned)record
{
    return self;
}

- source:aSource willWriteRecord:(unsigned)record
{
    return self;
}

